package cn.wilson.hrm.filter;

import cn.wilson.hrm.feign.client.RedisFeignClient;
import cn.wilson.hrm.utils.AjaxResult;
import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthCheckFilter extends ZuulFilter {

    @Autowired
    private RedisFeignClient redisFeignClient;


    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        //越小越先执行
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        //返回true执行run方法，反之不执行
        //不需要检查的url  比如登录注册

        //请求上下文对象
        RequestContext currentContext = RequestContext.getCurrentContext();

        //获取请求对象
        HttpServletRequest request = currentContext.getRequest();

        //获取URI
        String uri = request.getRequestURI();

        //判断是否有不做登录检查的地址
        if (uri.contains("/login") || uri.contains("/register") || uri.contains("/swagger-ui.html")){
            //放行
            return false;
        }
        return true;
    }

    /**
     *      做登录检查的
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        //请求上下文对象
        RequestContext currentContext = RequestContext.getCurrentContext();

        //获取请求对象
        HttpServletRequest request = currentContext.getRequest();

        //获取请求头  获取到token
        String token = request.getHeader("X-Token");

        //token为空的情况
        if (StringUtils.isBlank(token)){
            //没有token阻止继续执行返回错误信息
            authCheckError(currentContext);
        } else {
            //token是错误的情况
            AjaxResult ajaxResult = redisFeignClient.get(token);
            if(!ajaxResult.isSuccess() || ajaxResult.getResultObj() == null){
                //查询redis中token，没查询到
                //就执行上面的错误提示信息
                authCheckError(currentContext);
            }

        }

        return null;
    }

    private void authCheckError(RequestContext currentContext) {
        try {
            //为false 阻止继续执行
            currentContext.setSendZuulResponse(false);

            AjaxResult ajaxResult = AjaxResult.me().setMessage("请先登录！");
            //返回给浏览器
            HttpServletResponse response = currentContext.getResponse();
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(ajaxResult));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
